package work.mediway.mdm.biz.service.biz.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mediway.hos.app.base.seure.util.SecurityUtils;
import com.mediway.hos.messgateway.mapper.MessageHeaderMapper;
import com.mediway.hos.messgateway.model.entity.MessageHeader;
import com.mediway.hos.messgateway.model.entity.MessageType;
import com.mediway.hos.messgateway.model.entity.ServiceManage;
import com.mediway.hos.messgateway.service.MessageTypeService;
import com.mediway.hos.messgateway.service.ServiceManageService;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import work.mediway.mdm.core.enums.StatusEnum;
import work.mediway.mdm.core.enums.TablePrefixEnum;
import work.mediway.mdm.core.helper.BaseDatabaseHelper;
import work.mediway.mdm.core.page.QueryRequest;
import work.mediway.mdm.core.util.DUtil;
import work.mediway.mdm.core.exception.DataException;
import work.mediway.mdm.biz.entity.biz.SsInterSystems;
import work.mediway.mdm.biz.entity.biz.SsServiceLinkSystem;
import work.mediway.mdm.biz.entity.dict.CtCodeSystem;
import work.mediway.mdm.biz.mapper.biz.SsInterSystemsMapper;
import work.mediway.mdm.biz.service.biz.SsInterSystemsService;
import work.mediway.mdm.biz.service.biz.SsServiceLinkSystemService;
import work.mediway.mdm.biz.service.dict.CtCodeSystemService;
import work.mediway.mdm.biz.vo.biz.MessageStatisticsVO;
import work.mediway.mdm.biz.vo.biz.ServiceManageVO;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2022/6/22
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class SsInterSystemsServiceImpl extends ServiceImpl<SsInterSystemsMapper, SsInterSystems> implements SsInterSystemsService {

    private final BaseDatabaseHelper baseDatabaseHelper;
    private final ServiceManageService serviceManageService;
    private final SsServiceLinkSystemService serviceLinkSystemService;
    private final MessageHeaderMapper messageHeaderMapper;
    private final MessageTypeService messageTypeService;
    // TODO: 2022/9/30
    /*private final IAccessSystemService accessSystemService;*/
    private final CtCodeSystemService codeSystemService;

    @Override
    public Page<SsInterSystems> listInterSystem(SsInterSystems interSystems, QueryRequest queryRequest) {
        if (StrUtil.isNotBlank(interSystems.getTableCode())) {
            MessageType messageType = new MessageType();
            messageType.setTypeName(interSystems.getTableCode());
            List<MessageType> messageTypes = this.messageTypeService.selectAllMessageTypeList(messageType);
            if (CollUtil.isEmpty(messageTypes)) {
                return new Page<>();
            }
            for (String idStr : messageTypes.stream().map(MessageType::getTypeSubscribe).collect(Collectors.toList())) {
                interSystems.getMessageServiceIds().addAll(StrUtil.split(idStr, ","));
            }
            interSystems.setMessageServiceIds(interSystems.getMessageServiceIds().stream().distinct().collect(Collectors.toList()));
        }
        Page<SsInterSystems> page = new Page<>(queryRequest.getCurrent(), queryRequest.getSize());
        page.setRecords(this.baseMapper.selectInterSystem(page, interSystems));

        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveInterSystem(SsInterSystems interSystems) {
        if (ObjectUtil.isNotEmpty(this.getOne(Wrappers.lambdaQuery(SsInterSystems.class).eq(SsInterSystems::getSsisDesc, interSystems.getSsisDesc())))) {
            throw new DataException(StrUtil.format("新增接入系统'" + interSystems.getSsisDesc() + "'失败，名称已存在"));
        }
        if (StrUtil.isBlank(interSystems.getSsisCode())) {
            interSystems.setSsisCode(baseDatabaseHelper.buildCode(TablePrefixEnum.SS_InterSystems));
        }
        if (StrUtil.isBlank(interSystems.getSsisStatus())) {
            interSystems.setSsisCode(StatusEnum.STATUS_ACTIVE.getStatusCode());
        }
        interSystems.setSsisUpdateUserCode(SecurityUtils.getLoginName());
        interSystems.setSsisUpdateDate(DUtil.splitNow()[0]);
        interSystems.setSsisUpdateTime(DUtil.splitNow()[1]);
        this.save(interSystems);
        // 存储数据质量需要用的到系统信息
        // TODO: 2022/9/30
        /*AccessSystemDO accessSystem = new AccessSystemDO();
        accessSystem.setAccessSystemId(Long.valueOf(interSystems.getId()));
        accessSystem.setAccessName(interSystems.getSsisDesc());
        accessSystem.setCompany(interSystems.getSsisManufacturer());
        accessSystem.setStatus(interSystems.getSsisStatus());
        accessSystem.setCreateBy(SecurityUtils.getUsername());
        accessSystem.setUpdateBy(SecurityUtils.getUsername());
        this.accessSystemService.insertAccessSystem(accessSystem);*/
    }

    @Override
    public void saveInterService(SsServiceLinkSystem serviceLinkSystem) {
        ServiceManage serviceManage = serviceLinkSystem.getServiceManage();
        this.serviceManageService.insertServiceManage(serviceManage);
        serviceLinkSystem.setSsslsServiceId(serviceManage.getServiceId());
        serviceLinkSystem.setSsslsServiceDesc(serviceManage.getServiceName());
        serviceLinkSystem.setSsslsUpdateDate(DUtil.splitNow()[0]);
        serviceLinkSystem.setSsslsUpdatetime(DUtil.splitNow()[1]);
        serviceLinkSystem.setSsslsUpdateUserCode(SecurityUtils.getLoginName());
        this.serviceLinkSystemService.save(serviceLinkSystem);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateInterSystem(SsInterSystems interSystems) {
        if (ObjectUtil.isNotEmpty(this.getOne(Wrappers.lambdaQuery(SsInterSystems.class).eq(SsInterSystems::getSsisDesc, interSystems.getSsisDesc())))) {
            throw new DataException(StrUtil.format("编辑接入系统'" + interSystems.getSsisDesc() + "'失败，名称已存在"));
        }
        interSystems.setSsisUpdateUserCode(SecurityUtils.getLoginName());
        interSystems.setSsisUpdateDate(DUtil.splitNow()[0]);
        interSystems.setSsisUpdateTime(DUtil.splitNow()[1]);
        this.updateById(interSystems);
        // TODO: 2022/9/30
        /*AccessSystemDO accessSystem = new AccessSystemDO();
        accessSystem.setAccessSystemId(Long.valueOf(interSystems.getId()));
        accessSystem.setUpdateBy(SecurityUtils.getUsername());
        accessSystem.setAccessName(interSystems.getSsisDesc());
        accessSystem.setCompany(interSystems.getSsisManufacturer());
        accessSystem.setStatus(interSystems.getSsisStatus());
        this.accessSystemService.updateAccessSystem(accessSystem);*/
    }

    @Override
    public Page<ServiceManageVO> selectInterService(ServiceManage serviceManage, Long ssslsSystemId, QueryRequest queryRequest) {
        Page<ServiceManageVO> page = new Page<>(queryRequest.getCurrent(), queryRequest.getSize());
        page.setRecords(this.baseMapper.selectInterService(page, serviceManage, ssslsSystemId));
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateInterService(SsServiceLinkSystem serviceLinkSystem) {
        ServiceManage serviceManage = serviceLinkSystem.getServiceManage();
        if (ObjectUtil.isEmpty(this.serviceManageService.selectServiceManageByServiceId(serviceManage.getServiceId()))) {
            throw new DataException("serviceId = {} 数据不存在, 请先保存");
        }
        this.serviceManageService.updateServiceManage(serviceManage);
        if (StrUtil.isNotBlank(serviceLinkSystem.getSsslsSystemId())) {
            SsServiceLinkSystem ssServiceLinkSystem = this.serviceLinkSystemService.getById(serviceManage.getServiceId());
            if (ObjectUtil.isNotEmpty(ssServiceLinkSystem)) {
                this.serviceLinkSystemService.removeById(ssServiceLinkSystem.getSsslsServiceId());
            }
            serviceLinkSystem.setSsslsServiceId(serviceManage.getServiceId());
            serviceLinkSystem.setSsslsServiceDesc(serviceManage.getServiceName());
            serviceLinkSystem.setSsslsSystemId(serviceLinkSystem.getSsslsSystemId());
            serviceLinkSystem.setSsslsUpdateDate(DUtil.splitNow()[0]);
            serviceLinkSystem.setSsslsUpdatetime(DUtil.splitNow()[1]);
            serviceLinkSystem.setSsslsUpdateUserCode(SecurityUtils.getLoginName());
            this.serviceLinkSystemService.save(serviceLinkSystem);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteInterService(List<String> ids) {
        for (String id : ids) {
            this.serviceManageService.deleteServiceManageByServiceId(Long.valueOf(id));
            this.serviceLinkSystemService.removeById(Long.valueOf(id));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteInterSystem(List<String> ids) {
        for (String id : ids) {
            List<SsServiceLinkSystem> list = this.serviceLinkSystemService.list(Wrappers
                    .lambdaQuery(SsServiceLinkSystem.class).eq(SsServiceLinkSystem::getSsslsSystemId, id));
            if (CollUtil.isNotEmpty(list)) {
                throw new DataException(StrUtil.format("接入系统id = {} 已经被绑定, 不能删除", id));
            }
            // 删除数据采集表中数据
            // TODO: 2022/9/30
            /*this.accessSystemService.deleteAccessSystemByIds(new Long[]{Long.valueOf(id)});*/
            SsInterSystems interSystems = this.getById(id);
            // 更新字典列表中的绑定信息
            List<CtCodeSystem> codeSystems = this.codeSystemService.list(Wrappers.lambdaQuery(CtCodeSystem.class).eq(CtCodeSystem::getSourceSystem, interSystems.getSsisCode()));
            for (CtCodeSystem codeSystem : codeSystems) {
                codeSystem.setSourceSystem("");
                this.codeSystemService.updateById(codeSystem);
            }
            // 删除自身数据
            this.removeById(id);
        }
    }

    @Override
    public ServiceManageVO selectInterServiceByServiceId(Long serviceId) {
        ServiceManage manage = new ServiceManage();
        manage.setServiceId(serviceId);
        Page<ServiceManageVO> serviceManageVos = this.selectInterService(manage, null, new QueryRequest());
        if (CollUtil.isEmpty(serviceManageVos.getRecords())) {
            throw new DataException("serviceId = {} 未查询到数据");
        }
        for (ServiceManageVO serviceManage : serviceManageVos.getRecords()) {
            String[] headerIds;
            if (serviceManage.getHeaderIds() != null && !serviceManage.getHeaderIds().equals("")) {
                headerIds = serviceManage.getHeaderIds().substring(0, serviceManage.getHeaderIds().length() - 1).split(",");
                List<MessageHeader> messageHeaderList = CollUtil.newArrayList();
                String[] var5 = headerIds;
                int var6 = headerIds.length;

                for (int var7 = 0; var7 < var6; ++var7) {
                    String headerId = var5[var7];
                    MessageHeader messageHeader = this.messageHeaderMapper.selectMessageHeaderByHeaderId(Integer.parseInt(headerId));
                    if (messageHeader != null) {
                        messageHeaderList.add(messageHeader);
                    }
                }

                serviceManage.setMessageHeaderList(messageHeaderList);
            } else {
                serviceManage.setMessageHeaderList(CollUtil.newArrayList());
            }
        }
        return serviceManageVos.getRecords().get(0);
    }

    @Override
    public List<MessageStatisticsVO> selectStatisticsMessageList(String sendDate) {
        return this.baseMapper.selectStatisticsMessageList(sendDate);
    }
}
